package in.co.codedoc.json;

public class JSONStringValue
	extends JSONValue
{
	public JSONStringValue(String value,boolean quoted)
	{
		this.value = quoted ? RemoveEscapes(value) : value;
	}
	
	public JSONStringValue(String value)
	{
		this(value,false);
	}

	public JSONStringValue(JSONValue jsonValue)
	{
		if(jsonValue == null)
		{
			this.value = "";
		}
		else if(jsonValue instanceof JSONLongValue)
		{
			this.value = new Long(((JSONLongValue)jsonValue).GetValue()).toString();
		}
		else if(jsonValue instanceof JSONDoubleValue)
		{
			this.value = new Double(((JSONDoubleValue)jsonValue).GetValue()).toString();
		}
		else if(jsonValue instanceof JSONStringValue)
		{
			this.value = ((JSONStringValue)jsonValue).GetValue();
		}
		else
		{
			throw new RuntimeException("Dont know how to build a JSONStringValue from " + jsonValue.getClass());
		}
	}

	
	private String RemoveEscapes(String value)
	{
		StringBuffer buffer = new StringBuffer();
	
		if(value != null)
		{
			boolean afterSlash = false;
			for(int i = 0;i< value.length();i++)
			{
				char c = value.charAt(i);
				
				if(afterSlash)
				{
					switch(c)
					{
						case 'r':
							buffer.append('\r');
							break;
						case 'n':
							buffer.append('\n');
							break;
						case 't':
							buffer.append('\t');
							break;
						default:
							buffer.append(c);
					}
					afterSlash = false;
				}
				else
				{
					if(c == '\\')
					{
						afterSlash = true;
					}
					else
					{
						buffer.append(c);
					}
				}
			}
		}
		
		return buffer.toString();
	}

	@Override
	public String toString()
	{
		return value;
	}
	
	public String GetValue()
	{
		return value;
	}
	
	@Override
	public StringBuffer Encode(StringBuffer buffer)
	{
		buffer.append('"');
		if(value != null)
		{
			for(int i = 0; i< value.length();i++)
			{
				char c = value.charAt(i);
			
				if(c == '"' ||c == '\\')
				{
					buffer.append('\\');
				}
			
				buffer.append(c);
			}
		}
		buffer.append('"');
		return buffer;
	}

	@Override
	public boolean equals(Object t)
	{
		if((t == null) || !(t instanceof JSONStringValue))
		{
			return false;
		}

		JSONStringValue that = (JSONStringValue)t;
		
		return that.value == value;
	}

	@Override
	public int hashCode()
	{
		return value.hashCode();
	}

	private String value;
}
